import axios from 'axios'
import store from '@/store'
import { handleResponse, handleError } from './utils'

const instance = axios.create({
  baseURL: process.env.VUE_APP_BASEURL,
  validateStatus: function (status) {
    return status >= 200 && status < 300 // res.status超出这个范围会走失败的promise
  }
})
instance.interceptors.request.use(
  config => {
    // 防止IE浏览器get请求缓存
    if (config.method === 'get' && config.params) {
      config.params._t = +new Date()
    }
    return config
  },
  err => Promise.reject(err)
)
instance.interceptors.response.use(
  res => {
    // 只有当res.status==200 && res.data.code=='00000'时才是true，在这里做没登录或登录过期的处理
    const result = handleResponse(res)
    if (result) {
      return Promise.resolve(res.data)
    } else {
      return Promise.reject(res.data)
    }
  },
  err => {
    // 如果请求错误需要弹出提示
    handleError(err)
    return Promise.reject(err)
  }
)

function startLoading(showLoading) {
  if (showLoading) store.commit('STARTLOADING')
}
function endLoading(showLoading) {
  if (showLoading) store.commit('ENDLOADING')
}

// 封装get请求
export function get(url, params, config = {}, showLoading = true) {
  // 写在这里而不写在请求拦截中，写在请求拦截中，所有请求都会开启loading
  startLoading(showLoading)
  return instance({
    ...config,
    url,
    method: 'get',
    params
  }).then(
    res => {
      endLoading(showLoading)
      return Promise.resolve(res)
    },
    err => {
      endLoading(showLoading)
      return Promise.reject(err)
    }
  )
}

export function post(url, data, config = {}, showLoading = true) {
  startLoading(showLoading)
  return instance({
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    ...config,
    url,
    method: 'post',
    data
  }).then(
    res => {
      endLoading(showLoading)
      return Promise.resolve(res)
    },
    err => {
      endLoading(showLoading)
      return Promise.reject(err)
    }
  )
}
export function del(url, data, config = {}, showLoading = true) {
  startLoading(showLoading)
  return instance({
    ...config,
    url,
    method: 'delete',
    data
  }).then(
    res => {
      endLoading(showLoading)
      return Promise.resolve(res)
    },
    err => {
      endLoading(showLoading)
      return Promise.reject(err)
    }
  )
}
export function put(url, data, config = {}, showLoading = true) {
  startLoading(showLoading)
  return instance({
    ...config,
    url,
    method: 'put',
    data
  }).then(
    res => {
      endLoading(showLoading)
      return Promise.resolve(res)
    },
    err => {
      endLoading(showLoading)
      return Promise.reject(err)
    }
  )
}
export function patch(url, data, config = {}, showLoading = true) {
  startLoading(showLoading)
  return instance({
    ...config,
    url,
    method: 'patch',
    data
  }).then(
    res => {
      endLoading(showLoading)
      return Promise.resolve(res)
    },
    err => {
      endLoading(showLoading)
      return Promise.reject(err)
    }
  )
}
